#include "admin.h"

// 管理员登录验证
bool admin_login(const char *username, const char *password) {
    return (strcmp(username, DEFAULT_USERNAME) == 0 && 
            strcmp(password, DEFAULT_PASSWORD) == 0);
}

// 添加会员
bool add_user(user_imf user) {
    FILE *fp = fopen("./member_data.dat", "ab");
    if (!fp) return false;
    
    // 写入用户数据
    fwrite(&user, sizeof(user_imf), 1, fp);
    fclose(fp);
    return true;
}

// 删除会员(逻辑删除，标记为已删除状态)
bool del_user(unsigned int user_id) {
    FILE *fp = fopen("./member_data.dat", "rb+");
    if (!fp) return false;
    
    user_imf user;
    while (fread(&user, sizeof(user_imf), 1, fp) == 1) {
        if (user.user_id == user_id) {
            // 将用户状态改为已删除
            user.status = deleted;
            // 移动文件指针到当前用户位置
            fseek(fp, -sizeof(user_imf), SEEK_CUR);
            fwrite(&user, sizeof(user_imf), 1, fp);
            fclose(fp);
            return true;
        }
    }
    
    fclose(fp);
    return false;
}

// 更新用户信息
bool update_user(user_imf user) {
    FILE *fp = fopen("./member_data.dat", "rb+");
    if (!fp) return false;
    
    user_imf temp;
    while (fread(&temp, sizeof(user_imf), 1, fp) == 1) {
        if (temp.user_id == user.user_id) {
            // 将文件指针移回当前用户位置
            fseek(fp, -sizeof(user_imf), SEEK_CUR);
            // 写入更新后的用户信息
            fwrite(&user, sizeof(user_imf), 1, fp);
            fclose(fp);
            return true;
        }
    }
    
    fclose(fp);
    return false;
}

// 查找用户位置
int find_user_pos(unsigned int user_id) {
    FILE *fp = fopen("./member_data.dat", "rb");
    if (!fp) return -1;
    
    int pos = 0;
    user_imf user;
    while (fread(&user, sizeof(user_imf), 1, fp) == 1) {
        if (user.user_id == user_id) {
            fclose(fp);
            return pos;
        }
        pos++;
    }
    
    fclose(fp);
    return -1;
}

// 获取用户信息
void res_user(unsigned int user_id, user_imf *user) {
    FILE *fp = fopen("./member_data.dat", "rb");
    if (!fp) {
        memset(user, 0, sizeof(user_imf));
        return;
    }
    
    user_imf temp;
    while (fread(&temp, sizeof(user_imf), 1, fp) == 1) {
        if (temp.user_id == user_id) {
            *user = temp;
            fclose(fp);
            return;
        }
    }
    
    // 未找到用户
    memset(user, 0, sizeof(user_imf));
    fclose(fp);
}

// 列出所有用户
void list_all(user_imf **users, int *count) {
    FILE *fp = fopen("./member_data.dat", "rb");
    if (!fp) {
        *count = 0;
        *users = NULL;
        return;
    }
    
    // 先计算用户数量
    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    *count = file_size / sizeof(user_imf);
    rewind(fp);
    
    // 分配内存
    *users = malloc(*count * sizeof(user_imf));
    if (!*users) {
        *count = 0;
        fclose(fp);
        return;
    }
    
    // 读取所有用户
    fread(*users, sizeof(user_imf), *count, fp);
    fclose(fp);
}
    
